#include "Population.hh"


Population::Population() {
    this->solutions = new ArrayList<Solution>(true);
}


Population::Population(ArrayList<Solution> *solutions) {
    this->solutions = solutions;
    updateSum();
}

Population::~Population() {
    delete solutions;
}

void Population::replace(ArrayList<Solution> *newSolutions) {

    solutions->removeAll();
    solutions->addAll(newSolutions);

    updateSum();
}

Solution* Population::get(int i) {
    return solutions->get(i);
}

ArrayList<Solution>* Population::getAll() {
    return solutions;
}

ArrayList<Solution>* Population::getParetoFront() {

    ArrayList<Solution> *front = new ArrayList<Solution>(true);

    for (int i = 0; i < solutions->length(); i++) {
        Solution *solution = solutions->get(i);

        bool dominant = true;

        for (int j = 0; j < front->length(); j++) {
            Solution *frontSolution = front->get(j);

            if (frontSolution->equals(solution)) {
                dominant = false;
                break;
            }

            if (dominant && frontSolution->dominates(solution)) dominant = false;

            if (solution->dominates(frontSolution)) {
                front->remove(j);
                j--;
            }
        }

        if (dominant) front->add(solution->copy());
    }

    return front;
}

int Population::length() {
    return solutions->length();
}

double Population::getSum() {
    return sum;
}

void Population::updateSum() {
    sum = 0;

    for (int i = 0; i < solutions->length(); i++) sum += solutions->get(i)->getFitness();
}

